<template>
    <div>
        <el-upload
            ref="uploadRef"
            v-model:file-list="tempList"
            :auto-upload="autoUpload"
            :data="uploadData"
            :action="actionUrl"
            :accept="accept"
            :drag="drag"
            :limit="limit"
            :multiple="multiple"
            :class="limited"
            :disabled="disabled"
            :list-type="listType"
            :before-upload="beforeUpload"
            :on-change="handleChange"
		    :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-error="handleError"
        >
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <el-dialog v-model="visible">
            <img style="max-width: 100%;" :src="imageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
<script setup>
import {ref, computed, watch, nextTick} from "vue";
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import { getOssImage } from "@/api/api";
const actionUrl = computed(() => import.meta.env.VITE_APP_OSS)
const props = defineProps({
    modelValue: Array,
    drag: {type: Boolean, default: false},
    autoUpload: {type: Boolean, default: true},
    multiple: {type: Boolean, default: false},
    disabled: {type: Boolean, default: false},
    accept: {type: String, default: "image/*"},
    limit: {type: Number, default: 1},
    listType: {type: String, default: "picture-card"},
    class: String,
    style: String,
});
const emits = defineEmits([
    "update:modelValue",
    "success",
    "remove",
    "fc.el",
]);
const fileList = computed({
    get: () => {
        return props.modelValue
    },
    set: (val) => {
        emits("update:modelValue", val);
    }
});
const tempList = computed({
    get: () => {
        return props.modelValue.map((el, index) => {
            return {name: "name"+index,url: el};
        });
    },
    set: (val) => {
        return val;
    }
});
const uploadRef = ref();
const filePath = ref("");
const limited = ref("");
const visible = ref(false);
const imageUrl = ref("");
const uploadData = ref({});
const uploadDataList = ref([]);
const beforeUpload = async (file) => {
    if (file.size > (1024 * 1024 * 10)) {
        ElMessage.error("上传图片大小不能超过 10MB!");
        return false;
    }
    const {data} = await getOssImage({original_name: file.name});
    uploadData.value = {
        OSSAccessKeyId: data.upload_policy.access_key_id,
        policy: data.upload_policy.policy,
        signature: data.upload_policy.signature,
        key: data.upload_policy.key,
        name: data.upload_policy.name,
        success_action_status: 200
    }
    uploadDataList.value.push(data.upload_policy);
};
const handleExceed = (files, uploadFiles) => {
	if (files.length >= props.limit || fileList.value.length >= props.limit || (fileList.value.length + files.length) >= props.limit) {
		ElMessage.error(`最多上传${props.limit}张图片`)
	} else {
		ElMessage.error('上传图片错误，请重试')
	}
}
const handleSuccess = (res, file, files) => {
    if (files.every(item => item.status == 'success')) {
        const filePathList = uploadDataList.value.map(i => i.oss_file_url);
        fileList.value = [...fileList.value, ...filePathList];
        uploadDataList.value = [];
        emits("success", filePath.value, fileList.value);
      }
};
const handleChange = (uploadFile, uploadFiles) => {
    if (props.limit === 0) return;
    nextTick(()=>{
        limited.value = fileList.value.length >= props.limit ? "hide-trigger" : "";
    })
}
handleChange();
const handleRemove = (file) => {
    console.log("uploadRemove", file.url);
    let temp = [...fileList.value];
    let index = temp.indexOf(file.url);
    if (index > -1) {
        temp.splice(index, 1);
        fileList.value = temp;
    }
    handleChange();
    emits("remove", file.url, fileList.value);
};
const handleError = () => {
    ElMessage.error("上传失败，请重试！");
};
const handlePreview = (file) => {
    imageUrl.value = file.url;
    visible.value = true;
};
</script>
<style>
.el-upload--picture-card {
    margin: 0 8px 8px 0;
}
.hide-trigger .el-upload--picture-card{
    display: none;
}
</style>
<style lang="scss" scoped>
    :deep() {
        .el-upload-list__item {
            transition: none !important;
            -webkit-transition: none !important;
        }

        .el-upload-list__item-name {
            transition: none !important;
            -webkit-transition: none !important;
        }
        .el-upload-dragger {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
</style>